var Schema = require('mongoose').Schema;
var mongoose = require('../untils/mongodb');

var LiveSchema = new Schema({ 
	matchId: String,
	events: [],
	stats: [],
});

var LiveModelName = 'LIVE_EVENTS_STATS';

var LiveModel = mongoose.model(LiveModelName, LiveSchema);


var findById = function(matchId, cb) {
	LiveModel.findOne({matchId: matchId}, cb);
}

var saveLiveData = function(id, data) {
	var saveFn = function(doc) {
		doc.events = data.events;
		doc.stats = data.stats;
		doc.save(function(err) {
			if (err) {
				console.log(err);
			}
		})
	}

	findById(id, function(err, doc) {
		if (!doc) {
			doc = new LiveModel({
				matchId: id
			});
		}
		saveFn(doc);
	})
}

module.exports = {
	findById,
	saveLiveData
}